import base64
import hashlib
import hmac
import json
import os
import time
from urllib.parse import quote_plus

import requests

TOKEN = "0dcef55b700bd14888ce44c89a8d27beae9c64a5ca2dda2e17733c4fe2da35ee"
SECRET = "SEC637ec592497d22cfcdefa1a7f7d809542853777272558eb47dd6bb8c7a4a722a"


class DingTalk:

    def __init__(self, token=TOKEN, secret=SECRET):
        self.timestamp = str(round(time.time() * 1000))
        self.URL = "https://oapi.dingtalk.com/robot/send"
        self.headers = {'Content-Type': 'application/json'}
        secret = secret
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = quote_plus(base64.b64encode(hmac_code))
        self.params = {'access_token': token, "sign": self.sign}

    def send_text(self, content):
        """
        :param content: message to send
        :return:
        """
        data = {"msgtype": "text", "text": {"content": content}}
        self.params["timestamp"] = self.timestamp
        return requests.post(
            url=self.URL,
            data=json.dumps(data),
            params=self.params,
            headers=self.headers)

